<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
                @close="resetForm"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <!-- el-data：data属性用来指定数据源的 -->
            <el-table
              :data="roles"
            >
              <el-table-column
                label="序号"
                width="120"
                prop="num"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="hAssign(scope.row.id)"
                  >
                    分配权限
                  </el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="total"
                :page-size="params.pagesize"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="cTitle"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="resetForm"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button
              size="small"
              @click="showDialog=false"
            >取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showAssignDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-permission
          v-if="showAssignDialog"
          :role-id="roleId"
          @close-dialog="showAssignDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRoles, deleteRole, addRole, updateRole } from '@/api/settings'
import assignPermission from './assignPermission'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roleId: '',
      showAssignDialog: false, // 分配权限对话框
      activeName: 'first',
      roles: [],
      params: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      isEdit: false
    }
  },
  computed: {
    cTitle() {
      return this.isEdit ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    async loadRoles() {
      const res = await getRoles(this.params)
      console.log('所有角色信息', res)
      // 保存数据
      this.roles = res.data.rows
      this.total = res.data.total
      let num = 1
      this.roles.forEach(item => {
        //   每页上的数据序号等于前页页码*每页的数据量 + 从1自加的数
        item.num = (this.params.page - 1) * this.params.pagesize + num++
      })
    },
    hCurrentChange(curPage) {
      // 更新查询条件中的页码
      this.params.page = curPage
      // 再发一次请求
      this.loadRoles()
    },
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log(res)
        //   1.提示
        this.$message.success('删除成功')
        // 2.如果当前表格中只有一条，删除之后自动请求下一条
        if (this.roles.length === 1) {
          this.params.page--
          if (this.params.page <= 0) {
            this.params.page = 1
          }
        }
        // 3.重新请求
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击删除
    hDel(id) {
      console.log('要删除的id', id)
      this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 做删除
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res)
        this.loadRoles()
        this.$message.success('添加成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('添加失败')
      }
    },
    // 提交
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          // 做具体的添加动作
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 编辑
    hEdit({ id, name, description }) {
      // 1. 把当前的数据直接给表单
    //   this.roleForm = row
      this.roleForm = { id, name, description }
      // 2. 显示弹层
      this.showDialog = true
      //   3.设为编辑状态
      this.isEdit = true
    },
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)

        this.loadRoles()
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('编辑失败')
        console.log(err)
      }
    },
    resetForm() {
      this.$refs.roleForm.resetFields()
    },
    // 显示弹层
    hAssign(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    hCancel() {
    // 通过父组件去关闭弹层
      this.$emit('close-dialog')
    }
  }
}
</script>
